import React, { useEffect, useState } from 'react';
import { Modal, Button, Space, Table, Tag, Popconfirm, message, Dropdown, Tabs, Card, Statistic, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, PlayCircleOutlined, SoundOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  getCourseLessons,
  getCourseChapters,
  deleteLesson,
  deleteChapter,
  batchOperateLessons,
  reorderLessons,
  getCourseLessonStats,
} from '@/services/courseManagementApi';
import LessonForm from './LessonForm';
import ChapterForm from './ChapterForm';

interface LessonManagementProps {
  visible: boolean;
  course?: COURSE.CourseModel;
  onCancel: () => void;
}

const LessonManagement: React.FC<LessonManagementProps> = ({ visible, course, onCancel }) => {
  const [loading, setLoading] = useState(false);
  const [lessons, setLessons] = useState<COURSE.LessonModel[]>([]);
  const [chapters, setChapters] = useState<COURSE.ChapterModel[]>([]);
  const [stats, setStats] = useState<COURSE.CourseLessonStatistics | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  
  // 表单状态
  const [lessonFormVisible, setLessonFormVisible] = useState(false);
  const [chapterFormVisible, setChapterFormVisible] = useState(false);
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');
  const [currentLesson, setCurrentLesson] = useState<COURSE.LessonModel | undefined>();
  const [currentChapter, setCurrentChapter] = useState<COURSE.ChapterModel | undefined>();

  useEffect(() => {
    if (visible && course) {
      loadData();
    }
  }, [visible, course]);

  const loadData = async () => {
    if (!course) return;
    
    setLoading(true);
    try {
      const [lessonsRes, chaptersRes, statsRes] = await Promise.all([
        getCourseLessons(course.id),
        getCourseChapters(course.id),
        getCourseLessonStats(course.id),
      ]);

      setLessons(lessonsRes.data || []);
      setChapters(chaptersRes.data || []);
      setStats(statsRes.data);
    } catch (error) {
      console.error('加载数据失败:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 课时操作
  const handleCreateLesson = () => {
    setCurrentLesson(undefined);
    setEditMode('create');
    setLessonFormVisible(true);
  };

  const handleEditLesson = (record: COURSE.LessonModel) => {
    setCurrentLesson(record);
    setEditMode('edit');
    setLessonFormVisible(true);
  };

  const handleDeleteLesson = async (id: number) => {
    try {
      await deleteLesson(id);
      message.success('课时删除成功');
      loadData();
    } catch (error) {
      message.error('课时删除失败');
    }
  };

  // 章节操作
  const handleCreateChapter = () => {
    setCurrentChapter(undefined);
    setEditMode('create');
    setChapterFormVisible(true);
  };

  const handleEditChapter = (record: COURSE.ChapterModel) => {
    setCurrentChapter(record);
    setEditMode('edit');
    setChapterFormVisible(true);
  };

  const handleDeleteChapter = async (id: number) => {
    try {
      await deleteChapter(id);
      message.success('章节删除成功');
      loadData();
    } catch (error) {
      message.error('章节删除失败');
    }
  };

  // 批量操作
  const handleBatchOperation = async (action: string) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的课时');
      return;
    }

    try {
      await batchOperateLessons({
        action: action as any,
        lesson_ids: selectedRowKeys,
      });
      message.success('批量操作成功');
      setSelectedRowKeys([]);
      loadData();
    } catch (error) {
      message.error('批量操作失败');
    }
  };

  // 格式化时长
  const formatDuration = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  // 课时表格列
  const lessonColumns: ColumnsType<COURSE.LessonModel> = [
    {
      title: '排序',
      dataIndex: 'sort_order',
      width: 80,
      sorter: (a, b) => a.sort_order - b.sort_order,
    },
    {
      title: '课时标题',
      dataIndex: 'title',
      ellipsis: true,
    },
    {
      title: '所属章节',
      dataIndex: 'chapter_id',
      width: 120,
      render: (chapterId) => {
        if (!chapterId) return '无章节';
        const chapter = chapters.find(c => c.id === chapterId);
        return chapter?.title || '无章节';
      },
    },
    {
      title: '时长',
      dataIndex: 'duration',
      width: 80,
      render: (duration) => formatDuration(duration),
    },
    {
      title: '媒体',
      width: 100,
      render: (_, record) => (
        <Space>
          {record.video_url && <PlayCircleOutlined style={{ color: '#1890ff' }} title="有视频" />}
          {record.audio_url && <SoundOutlined style={{ color: '#52c41a' }} title="有音频" />}
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'is_free',
      width: 80,
      render: (isFree) => (
        <Tag color={isFree ? 'green' : 'orange'}>
          {isFree ? '免费' : '付费'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      width: 80,
      render: (isActive) => (
        <Tag color={isActive ? 'green' : 'red'}>
          {isActive ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '观看数',
      dataIndex: 'view_count',
      width: 80,
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditLesson(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个课时吗？"
            onConfirm={() => handleDeleteLesson(record.id)}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 章节表格列
  const chapterColumns: ColumnsType<COURSE.ChapterModel> = [
    {
      title: '排序',
      dataIndex: 'sort_order',
      width: 80,
      sorter: (a, b) => a.sort_order - b.sort_order,
    },
    {
      title: '章节标题',
      dataIndex: 'title',
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '课时数',
      dataIndex: 'lesson_count',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditChapter(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个章节吗？删除后章节下的课时将移到无章节分组。"
            onConfirm={() => handleDeleteChapter(record.id)}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  if (!course) return null;

  return (
    <>
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div>
              <div>{course.title} - 课时管理</div>
              <div style={{ fontSize: '12px', color: '#666' }}>管理课程的章节和课时</div>
            </div>
          </div>
        }
        open={visible}
        onCancel={onCancel}
        footer={[
          <Button key="close" onClick={onCancel}>
            关闭
          </Button>,
        ]}
        width={1200}
        destroyOnClose
      >
        {/* 统计信息 */}
        {stats && (
          <Card style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={6}>
                <Statistic title="总课时数" value={stats.total_lessons} />
              </Col>
              <Col span={6}>
                <Statistic title="活跃课时" value={stats.active_lessons} />
              </Col>
              <Col span={6}>
                <Statistic title="免费课时" value={stats.free_lessons} />
              </Col>
              <Col span={6}>
                <Statistic 
                  title="总时长" 
                  value={Math.floor(stats.total_duration / 60)} 
                  suffix="分钟" 
                />
              </Col>
            </Row>
          </Card>
        )}

        <Tabs
          items={[
            {
              key: 'lessons',
              label: '课时管理',
              children: (
                <div>
                  <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
                    <Space>
                      <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleCreateLesson}
                      >
                        添加课时
                      </Button>
                      {selectedRowKeys.length > 0 && (
                        <Dropdown
                          menu={{
                            items: [
                              { key: 'activate', label: '批量启用', onClick: () => handleBatchOperation('activate') },
                              { key: 'deactivate', label: '批量禁用', onClick: () => handleBatchOperation('deactivate') },
                              { key: 'set_free', label: '设为免费', onClick: () => handleBatchOperation('set_free') },
                              { key: 'set_paid', label: '设为付费', onClick: () => handleBatchOperation('set_paid') },
                              { type: 'divider' },
                              { key: 'delete', label: '批量删除', danger: true, onClick: () => handleBatchOperation('delete') },
                            ],
                          }}
                        >
                          <Button icon={<MoreOutlined />}>
                            批量操作 ({selectedRowKeys.length})
                          </Button>
                        </Dropdown>
                      )}
                    </Space>
                  </div>

                  <Table
                    columns={lessonColumns}
                    dataSource={lessons}
                    rowKey="id"
                    loading={loading}
                    rowSelection={{
                      selectedRowKeys,
                      onChange: setSelectedRowKeys,
                    }}
                    scroll={{ x: 1000 }}
                    pagination={{
                      showSizeChanger: true,
                      showQuickJumper: true,
                    }}
                  />
                </div>
              ),
            },
            {
              key: 'chapters',
              label: '章节管理',
              children: (
                <div>
                  <div style={{ marginBottom: 16 }}>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleCreateChapter}
                    >
                      添加章节
                    </Button>
                  </div>

                  <Table
                    columns={chapterColumns}
                    dataSource={chapters}
                    rowKey="id"
                    loading={loading}
                    scroll={{ x: 800 }}
                    pagination={{
                      showSizeChanger: true,
                      showQuickJumper: true,
                    }}
                  />
                </div>
              ),
            },
          ]}
        />
      </Modal>

      {/* 课时表单 */}
      <LessonForm
        visible={lessonFormVisible}
        mode={editMode}
        courseId={course.id}
        initialValues={currentLesson}
        onCancel={() => setLessonFormVisible(false)}
        onSuccess={() => {
          setLessonFormVisible(false);
          loadData();
        }}
      />

      {/* 章节表单 */}
      <ChapterForm
        visible={chapterFormVisible}
        mode={editMode}
        courseId={course.id}
        initialValues={currentChapter}
        onCancel={() => setChapterFormVisible(false)}
        onSuccess={() => {
          setChapterFormVisible(false);
          loadData();
        }}
      />
    </>
  );
};

export default LessonManagement;
